package com.easyaop.api.advisor;

import com.easyaop.api.Context;
import com.easyaop.api.pointcut.Pointcut;
import com.easyaop.api.event.listener.MethodListener;

import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.stream.Collectors;

public class EventAdvisor extends Advisor {
    private Set<MethodListener> listeners = new LinkedHashSet<>();

    public EventAdvisor(Pointcut pointcut) {
        super(pointcut);
    }

    public synchronized void addListener(MethodListener listener) {
        listeners.add(listener);
        Context.addListener(signatures, Collections.singleton(listener));
    }

    public synchronized void addSignature(String signature) {
        boolean added = signatures.add(signature);
        if (added && !listeners.isEmpty()) {
            Context.addListener(Collections.singleton(signature), listeners);
        }
    }

    public synchronized void removeListener(MethodListener listener) {
        listeners.remove(listener);
        Context.removeListener(signatures, Collections.singleton(listener));
    }

    public synchronized void removeListener(Class<? extends MethodListener> listener) {
        Set<MethodListener> deleteListeners = listeners.stream()
                .filter(value -> value.getClass().equals(listener))
                .collect(Collectors.toSet());

        listeners.removeAll(deleteListeners);

        Context.removeListener(signatures, deleteListeners);
//        deleteListeners.stream().forEach(value -> Context.removeListener(signatures, value));
//        Context.removeListener(signatures, listener);
    }
}
